//
//  AnswerVC.m
//  ATAInterview
//
//  Created by up72-17 on 2018/12/11.
//  Copyright © 2018 up72-17. All rights reserved.
//

#import "AnswerVC.h"

#import "MainVC.h"

@interface AnswerVC ()

@end

@implementation AnswerVC

- (void)dealloc {
    NSLog(@"AudioQuestionsVC dealloc");
}

- (void)releaseMe {
    if (myTime.isValid) {
        [myTime invalidate];
    }
    if (fiveTime.isValid) {
        [fiveTime invalidate];
    }
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSLog(@"123");
    if (!isCamera) {
        if ([self camera]) {
            [self startRecord];
        }
    }
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [MTool setViewRadius:70 view:circleView];
    
    
    NSString *title = @"";
    
    if ([GlobalData sharedGlobalData].isSimulation) {
        if ([GlobalData sharedGlobalData].questionIndex == 0) {
            title = [NSString stringWithFormat:@"模拟试题1/%ld", [GlobalData sharedGlobalData].totalQuestion];
        } else if ([GlobalData sharedGlobalData].questionIndex == 1) {
            title = [NSString stringWithFormat:@"模拟试题2/%ld", [GlobalData sharedGlobalData].totalQuestion];
        } else if ([GlobalData sharedGlobalData].questionIndex == 2) {
            title = [NSString stringWithFormat:@"模拟试题3/%ld", [GlobalData sharedGlobalData].totalQuestion];
        } else if ([GlobalData sharedGlobalData].questionIndex == 3) {
            title = [NSString stringWithFormat:@"模拟试题4/%ld", [GlobalData sharedGlobalData].totalQuestion];
        }
    } else {
        if ([GlobalData sharedGlobalData].questionIndex == 0) {
            title = [NSString stringWithFormat:@"试题1/%ld", [GlobalData sharedGlobalData].totalQuestion];
        } else if ([GlobalData sharedGlobalData].questionIndex == 1) {
            title = [NSString stringWithFormat:@"试题2/%ld", [GlobalData sharedGlobalData].totalQuestion];
        } else if ([GlobalData sharedGlobalData].questionIndex == 2) {
            title = [NSString stringWithFormat:@"试题3/%ld", [GlobalData sharedGlobalData].totalQuestion];
        } else if ([GlobalData sharedGlobalData].questionIndex == 3) {
            title = [NSString stringWithFormat:@"试题4/%ld", [GlobalData sharedGlobalData].totalQuestion];
        }
    }
    
    [titleLabel setText:title];
    
    
    
    timeProgressView.transform = CGAffineTransformMakeScale(1.0, 4.0);
    
    [timeProgressView setProgressTintColor:kColorWithRGB(0x00D985)];
    [timeProgressView setTrackTintColor:kColorWithRGB(0xD1F8E9)];
    
    [MTool setViewRadius:6 view:timeProgressView];
    
    [timeProgressView setProgress:0];
    
    totalTime = 180;
    
    isCamera = NO;
    
    processView = [[SABCircleProcessView alloc] initWithFrame:fiveSecondsContentBackView.bounds];
    [fiveSecondsContentBackView addSubview:processView];
    processView.ovalShapeLayer.strokeEnd = 1;
    
    if ([self camera]) {
        [self startRecord];
    }
    
}


- (void)startRecord {
    
    if (isCamera) {
        return;
    }
    timeIndex = totalTime;
    
    [timeProgressView setProgress:0];
    
    myTime = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timeing) userInfo:nil repeats:YES];
    
    fiveTime = [NSTimer timerWithTimeInterval:0.1f target:self selector:@selector(startFiveProgress) userInfo:nil repeats:YES];
    
    
    isCamera = YES;
    WCLRecordVideoVC *record = [[WCLRecordVideoVC alloc] init];
    [record.view setFrame:recordbackView.bounds];
    [self addChildViewController:record];
    [recordbackView addSubview:record.view];
    
    
}



- (void)timeing {
    
    if (timeIndex <= 0) {
        [myTime invalidate];
        [self stopRecord:nil];
    }
    
    if (timeIndex == 5) {
        fiveTimeIndex = 50;
        [[NSRunLoop currentRunLoop] addTimer:fiveTime forMode:NSRunLoopCommonModes];
        [fiveSecondsView setHidden:NO];
        
    }
    [fiveSecondsLabel setText:[NSString stringWithFormat:@"%ld", (long)timeIndex]];
    
    [timeLabel setText:[MTool convertTime:timeIndex]];
    [timeProgressView setProgress:((CGFloat)totalTime - (CGFloat)timeIndex) / (CGFloat)totalTime];
    
    
    timeIndex--;
    
    //    NSLog(@"timeIndex = %ld", (long)timeIndex);
}

- (void)startFiveProgress {
    
    fiveTimeIndex--;
    
    if (fiveTimeIndex <= 0) {
        [fiveSecondsView setHidden:YES];
        [fiveTime invalidate];
    }
    
    processView.ovalShapeLayer.strokeEnd = ((CGFloat)fiveTimeIndex) / 50.0f;
    
}






- (BOOL)camera {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied)) {
        // 无相机权限 做一个友好的提示
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"申请使用相机和麦克风" message:@"请到“设置-隐私-相机和麦克风”中设置为允许访问" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *setAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if( [[UIApplication sharedApplication]canOpenURL:url] ) {
                [[UIApplication sharedApplication]openURL:url];
            }
        }];
        
        __weak typeof(self)weakSelf = self;
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf backToMain];
        }];
        
        [alert addAction:setAction];
        [alert addAction:cancelAction];
        
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_sync(dispatch_get_main_queue(), ^{
                    [self camera];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else {
        return YES;
    }
    return NO;
}


- (void)backToMain {
    [self releaseMe];
    NSArray *temp = self.navigationController.viewControllers;
    for (NSInteger i = 0; i < [temp count]; i++) {
        id tempvc = [temp objectAtIndex:i];
        if ([tempvc isKindOfClass:[MainVC class]]) {
            [self.navigationController popToViewController:tempvc animated:YES];
            return;
        }
    }
}


- (IBAction)backButtonAction:(UIButton *)sender {
//    [self releaseMe];
//    [self.navigationController popViewControllerAnimated:YES];
    [self backToMain];
}


- (IBAction)stopRecord:(id)sender {
    NSInteger temp = [GlobalData sharedGlobalData].questionIndex + 1;
    if (temp < [GlobalData sharedGlobalData].totalQuestion) {
        [[GlobalData sharedGlobalData] setQuestionIndex:temp];
        if ([GlobalData sharedGlobalData].questionIndex == 3) {
            VideoQuestionsVC *video = [[VideoQuestionsVC alloc] init];
            [self.navigationController pushViewController:video animated:YES];
        } else {
            AudioQuestionsVC *audioQuestions = [[AudioQuestionsVC alloc] init];
            [self.navigationController pushViewController:audioQuestions animated:YES];
        }
    } else {//回答完了
        if ([GlobalData sharedGlobalData].isSimulation) {//模拟
            SimulationFinishVC *simululation = [[SimulationFinishVC alloc] init];
            [self.navigationController pushViewController:simululation animated:YES];
        } else {//正式
            InterviewFinishVC *interview = [[InterviewFinishVC alloc] init];
            [self.navigationController pushViewController:interview animated:YES];
        }
    }
}








@end
